package com.wg.admin.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.wg.common.annotation.Log;
import com.wg.common.core.controller.BaseController;
import com.wg.common.core.domain.PageQuery;
import com.wg.common.core.domain.R;
import com.wg.common.core.domain.TableDataInfo;
import com.wg.common.enums.BusinessType;
import com.wg.common.exception.ServiceException;
import com.wg.common.utils.FileUtils;
import com.wg.system.entity.SysFile;
import com.wg.system.service.SysFileService;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * OSS对象存储表(SysFile)控制层
 *
 * @author wg
 * @date 2022-05-06 11:18:25
 */
@Validated
@Api(value = "对象存储控制器", tags = {"对象存储管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/oss")
public class SysFileController extends BaseController {

    private final SysFileService sysFileService;

    /**
     * 查询OSS对象存储列表
     */
    @ApiOperation("查询OSS对象存储列表")
    @SaCheckPermission("system:oss:list")
    @GetMapping("/list")
    public TableDataInfo<SysFile> list(SysFile file, PageQuery pageQuery) {
        return sysFileService.queryPageList(file, pageQuery);
    }

    /**
     * 上传文件
     */
    @ApiOperation("上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", paramType = "query", dataTypeClass = File.class, required = true)
    })
    @SaCheckPermission("system:oss:upload")
    @Log(title = "对象存储", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public R<Map<String, String>> upload(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            throw new ServiceException("上传文件不能为空");
        }
        SysFile sysFile = sysFileService.upload(file);
        Map<String, String> map = new HashMap<>(2);
        map.put("url", sysFile.getUrl());
        map.put("fileName", sysFile.getFileName());
        return R.ok(map);
    }

    @ApiOperation("下载文件")
    @SaCheckPermission("system:oss:download")
    @GetMapping("/download/{id}")
    public void download(@ApiParam("文件id") @PathVariable Long id, HttpServletResponse response) throws IOException {
        SysFile sysFile = sysFileService.getById(id);
        if (ObjectUtil.isNull(sysFile)) {
            throw new ServiceException("文件数据不存在!");
        }
        response.reset();
        FileUtils.setAttachmentResponseHeader(response, sysFile.getOriginalName());
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE + "; charset=UTF-8");
        long data;
        try {
            data = HttpUtil.download(sysFile.getUrl(), response.getOutputStream(), false);
        } catch (HttpException e) {
            if (e.getMessage().contains("403")) {
                throw new ServiceException("无读取权限, 请在对应的OSS开启'公有读'权限!");
            } else {
                throw new ServiceException(e.getMessage());
            }
        }
        response.setContentLength(Convert.toInt(data));
    }

    /**
     * 删除OSS对象存储
     */
    @ApiOperation("删除OSS对象存储")
    @SaCheckPermission("system:oss:remove")
    @Log(title = "OSS对象存储", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@ApiParam("OSS对象ID串")
                          @NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(sysFileService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }

}


